package com.cls.mc_demo.config;

import com.cls.mc_demo.common.Const;
import com.cls.mc_demo.common.HexStringUtil;
import com.cls.mc_demo.common.SPPacket;
import org.tio.client.ClientChannelContext;
import org.tio.client.ReconnConf;
import org.tio.client.TioClient;
import org.tio.client.TioClientConfig;
import org.tio.core.Node;
import org.tio.core.Tio;

/**
 * TCP客户端配置
 *
 * @author CLS
 * @since 2023/08/04
 */
public class CustomClientConfig {


    private static ClientChannelContext clientChannelContext = null;

    /**
     * Modbus TCP/IP启动
     */
    public static void start(String service, Integer port) throws Exception {
        //服务器节点
        Node serverNode = new Node(service, port);

        //handler, 包括编码、解码、消息处理
        CustomClientAioHandler tioClientHandler = new CustomClientAioHandler();

        //事件监听器，可以为null，但建议自己实现该接口，可以参考showcase了解些接口
        CustomClientTioMonitor clientTioMonitor = new CustomClientTioMonitor();

        //断链后自动连接的，不想自动连接请设为null
        ReconnConf reconnConf = new ReconnConf(5000L);

        //一组连接共用的上下文对象
        TioClientConfig tioClientConfig = new TioClientConfig(tioClientHandler, clientTioMonitor, reconnConf);


        tioClientConfig.setHeartbeatTimeout(Const.HEARTBEAT_TIMEOUT);
        TioClient tioClient = new TioClient(tioClientConfig);
        clientChannelContext = tioClient.connect(serverNode);
    }

    public static void send(String msg) {
        SPPacket packet = new SPPacket();
        packet.setBody(HexStringUtil.hexToByteArray(msg));
        Tio.send(clientChannelContext, packet);
    }
}
